import { nextTick } from 'vue';
import { getCourseWords, updateWordStatus } from '@/api/readings';

/**
 * 单词学习管理模块
 * @param {string} courseId - 当前课程ID
 * @param {Object} wordData - 单词数据响应式对象
 * @param {Object} ui - UI状态响应式对象
 * @param {Object} speech - 语音模块
 * @param {Object} WORD_STATUS - 单词状态常量
 * @param {Object} sessionProgress - 会话学习进度记录
 */
export const useWordLearning = (courseId, wordData, ui, speech, WORD_STATUS, sessionProgress) => {
  // 当前响应类型（know/fuzzy/unknown）
  let currentResponse = null;
  
  /**
   * 加载单词数据
   */
  const loadWordData = async () => {
    try {
      const response = await getCourseWords(courseId);
      if (response.code !== 0 || !response.data) {
        throw new Error(response.msg || '获取单词列表失败');
      }
        
      const formattedWords = response.data.words.map(word => 
        formatWord(word, response.data.study_ids)
      );
      
      [wordData.knownQueue, wordData.learningQueue] = formattedWords.reduce(
        (acc, word) => {
          acc[word.status === WORD_STATUS.KNOWN ? 0 : 1].push(word);
          return acc;
        },
        [[], []]
      );

      wordData.currentWord = wordData.learningQueue[0] ?? null;
      wordData.learningState = {
        totalWords: formattedWords.length,
        learnedWords: wordData.knownQueue.length,
        currentWordIndex: 0,
        totalVocabularyProgress: {
          totalLearnedWords: wordData.knownQueue.length,
          totalWords: formattedWords.length
        }
      };
    } catch (error) {
      console.error('获取单词列表失败:', error);
      // 这里可以集成消息提示
    }
  };
  
  /**
   * 格式化单词数据
   * @param {Object} word - API返回的单词数据
   * @param {Array<string>} studyIds - 已学习的单词ID列表
   * @returns {Object} 格式化后的单词数据
   */
  const formatWord = (word, studyIds = []) => ({
    id: word.id,
    content: word.content,
    usphone: word.usphone || '',
    ukphone: word.ukphone || '',
    phonetic: word.ukphone || word.usphone || '',
    definition: word.trans?.map(t => `${t.pos ? `[${t.pos}] ` : ''}${t.tran_cn}`).join('\n') || '',
    example: word.sentences && word.sentences.length > 0 ? {
      text: word.sentences[0].s_content,
      translation: word.sentences[0].s_cn || '',
      highlight: word.content
    } : null,
    relatedWords: (word.rel_words || [])
      .filter(rw => rw.hwd && rw.word_pos)
      .map(rw => ({
        word: rw.hwd,
        definition: rw.word_pos.map(wp => wp.tran_cn).join('\n'),
        partOfSpeech: rw.word_pos[0]?.pos || ''
      })),
    wordFamily: word.rem || '',
    status: word.study_status?.status || (studyIds.includes(word.id) ? WORD_STATUS.KNOWN : WORD_STATUS.UNLEARNED),
    // 新增的记忆相关参数
    percentage: word.percentage || 0,
    recognized_count: word.recognized_count || 0,
    unrecognized_count: word.unrecognized_count || 0,
    ambiguous_count: word.ambiguous_count || 0
  });
  
  /**
   * 计算单词记忆质量q
   * @param {Object} word - 单词对象
   * @returns {number} 记忆质量q (2-5)
   */
  const calculateMemoryQuality = (word) => {
    const { unrecognized_count, ambiguous_count } = word;
    
    if (unrecognized_count > 1) {
      return 2;
    } else if (unrecognized_count === 1 || ambiguous_count > 1) {
      return 3;
    } else if (ambiguous_count === 1) {
      return 4;
    } else if (ambiguous_count === 0 && unrecognized_count === 0) {
      return 5;
    }
    return 3; // 默认值
  };

  /**
   * 将单词插入到指定位置
   * @param {number} insertPosition - 插入位置（从当前位置开始计算）
   */
  const insertWordToPosition = (insertPosition) => {
    const word = wordData.learningQueue.shift();
    if (!word) return;

    // 确保插入位置不超过队列长度
    const actualPosition = Math.min(insertPosition, wordData.learningQueue.length);
    wordData.learningQueue.splice(actualPosition, 0, word);
    
    // 更新当前单词为队列第一个
    wordData.currentWord = wordData.learningQueue[0] ?? null;
  };

  /**
   * 第一阶段：处理用户对单词熟悉度的选择
   * @param {string} type - 响应类型：know/fuzzy/unknown
   */
  const handleResponse = (type) => {
    if (!wordData.currentWord) return;

    const word = wordData.currentWord;
    
    // 根据当前单词状态和选择类型更新参数
    if (word.status === WORD_STATUS.UNLEARNED) {
      if (type === 'know') {
        word.percentage += 100;
        word.recognized_count += 1;
      } else if (type === 'fuzzy') {
        word.percentage += 35;
        word.ambiguous_count += 1;
      } else if (type === 'unknown') {
        word.percentage = 0;
        word.unrecognized_count += 1;
      }
      word.status = WORD_STATUS.KNOWN;
    } else if (word.status === WORD_STATUS.KNOWN) {
      if (type === 'know') {
        word.percentage += 60;
        word.recognized_count += 1;
      } else if (type === 'fuzzy') {
        word.percentage += 35;
        word.ambiguous_count += 1;
      } else if (type === 'unknown') {
        word.percentage = 0;
        word.unrecognized_count += 1;
      }
    }

    // 记录当前选择的类型，用于第二阶段操作
    currentResponse = type;
    
    // 显示释义，进入第二阶段
    ui.showDefinition = true;
  };
  
  /**
   * 更新单词学习状态
   * @param {Object} word - 单词对象
   * @param {number} quality - 记忆质量q
   */
  const updateWordStatusFn = async (word, quality) => {
    try {
      await updateWordStatus({
        word_id: word.id,
        course_id: courseId,
        quality: quality,
        recognized_count: word.recognized_count,
        unrecognized_count: word.unrecognized_count,
        ambiguous_count: word.ambiguous_count,
      });
    } catch (error) {
      console.error('更新单词状态失败:', error);
    }
  };

  /**
   * 将当前单词移到已知队列
   */
  const moveToKnownQueue = () => {
    const word = wordData.learningQueue.shift();
    if (!word) return;

    word.status = WORD_STATUS.KNOWN;
    wordData.knownQueue.push(word);
    wordData.currentWord = wordData.learningQueue[0] ?? null;
    
    const { learningState } = wordData;
    learningState.learnedWords = wordData.knownQueue.length;
    learningState.totalVocabularyProgress.totalLearnedWords = wordData.knownQueue.length;
  };

  /**
   * 将当前单词移到学习队列末尾
   */
  const moveToEndOfLearningQueue = () => {
    const word = wordData.learningQueue.shift();
    if (!word) return;

    word.status = WORD_STATUS.UNKNOWN;
    wordData.learningQueue.push(word);
    wordData.currentWord = wordData.learningQueue[0] ?? null;
  };

  /**
   * 第二阶段：处理"下一词"按钮点击
   */
  const handleNextWord = async () => {
    if (!wordData.currentWord || !currentResponse) return;

    const word = wordData.currentWord;
    
    // 检查百分比是否>=100%
    if (word.percentage >= 100) {
      // 计算记忆质量q
      const quality = calculateMemoryQuality(word);
      
      // 发送更新状态请求
      updateWordStatusFn(word, quality);
      
      // 移到已知队列
      moveToKnownQueue();
      
      // 更新会话进度
      sessionProgress.learned++;
      sessionProgress.needsSaving = true;
    } else {
      // 根据第一阶段的选择和当前状态执行相应的队列操作
      if (word.status === WORD_STATUS.UNLEARNED) {
        if (currentResponse === 'fuzzy') {
          insertWordToPosition(6); // 插入到6个单词后
        } else if (currentResponse === 'unknown') {
          insertWordToPosition(3); // 插入到3个单词后
        } else {
          // know 情况下移除当前单词，直接下一个
          wordData.learningQueue.shift();
          wordData.currentWord = wordData.learningQueue[0] ?? null;
        }
      } else if (word.status === WORD_STATUS.KNOWN) {
        if (currentResponse === 'know') {
          insertWordToPosition(10); // 插入到10个单词后
        } else if (currentResponse === 'fuzzy') {
          insertWordToPosition(6); // 插入到6个单词后
        } else if (currentResponse === 'unknown') {
          insertWordToPosition(3); // 插入到3个单词后
        }
      }
    }
    
    // 重置UI状态，准备下一个单词的第一阶段
    ui.showDefinition = false;
    currentResponse = null;
    await nextTick();
  };
  
  /**
   * 第二阶段：处理"记错了"按钮点击
   */
  const handleWrong = async () => {
    if (!wordData.currentWord) return;

    const word = wordData.currentWord;
    
    // 重置参数，相当于点击"忘记"
    word.percentage = 0;
    word.unrecognized_count += 1;
    
    // 将单词插入到3个单词后
    insertWordToPosition(3);
    
    // 重置UI状态，准备下一个单词的第一阶段
    ui.showDefinition = false;
    currentResponse = null;
  };

  return {
    loadWordData,
    handleResponse,
    handleNextWord,
    handleWrong
  };
}; 